<%--
  Created by IntelliJ IDEA.
  User: 13939
  Date: 2024/11/27
  Time: 17:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.wy.util.DBUtil" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.time.LocalDateTime" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.time.temporal.ChronoUnit" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../styles/showStyles.css">

    <title>新闻标题</title>
</head>
<body>

<%
    //检测用户是否已经登陆了
    String username  = (String) session.getAttribute("username");


    if(username==null){
        response.sendRedirect("/login/login.jsp");
        return;  //!!!!!不能少  返回  不执行下面的语句
    }else{
%>

<header>
    <nav>
        <div class="dropdown">
            <%
                int uid =(int) session.getAttribute("uid");
                String sql=
                        "select nick_name  from news_user where uid='"+uid+"' ";
                DBUtil dbUtil=new DBUtil();
                ResultSet rs=dbUtil.query(sql);
                while(rs.next()){
            %>
            <button class="dropbtn" action="/user/login" >您好:<%=rs.getString("nick_name")%>▼</button>
            <div class="dropdown-content">
                <a href="../news/publishNews.jsp">发布新闻</a>
                <a href="../login/logout.jsp">退出登录</a>
            </div>
            <%}%>
        </div>
        <ul>
            <li><a href="show.jsp?type=1">新闻</a></li>
            <li><a href="show.jsp?type=2">体育</a></li>
            <li><a href="show.jsp?type=3">娱乐</a></li>
            <li><a href="show.jsp?type=4">科技</a></li>
            <li><a href="show.jsp?">其他</a></li>
        </ul>
    </nav>
</header>



<div class="container mt-5">
    <section class="news-list">
        <!-- 新闻条目将在这里动态生成 -->
    </section>

    <!-- 分页控件 -->
    <nav aria-label="Page navigation example" >
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页按钮将在这里动态生成 -->
        </ul>
    </nav>
</div>
<script>
    // 假设这是你的新闻数据
    /*const newsData = [
        { title: '特色产业激发乡村振兴新活力', views: re, hoursAgo: 630 },
        { title: '科技改变生活', views: 20, hoursAgo: 300 },
        { title: '环保行动进行时', views: 15, hoursAgo: 120 },
        // 更多新闻条目...
    ];*/
    const  newsData=[];
    <%
    String type1 = request.getParameter("type");

    String sqlheadline="";
    if(type1==null){
        sqlheadline="select * from news_headline";
    }else {
        int i = Integer.parseInt(type1);
        sqlheadline="select * from news_headline where type = "+i;
    }
    ResultSet rsheadline=dbUtil.query(sqlheadline);

    while(rsheadline.next()){
        Integer tid = rsheadline.getInt("type");
        String sqltype = "select tname from news_type where tid='" + tid + "' ";
        ResultSet rstype = dbUtil.query(sqltype);
        rstype.next();
        // 获取创建时间
        Timestamp createdTime = rsheadline.getTimestamp("update_time");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 将 Timestamp 转换为 LocalDateTime
        LocalDateTime createdLocalDateTime = createdTime.toLocalDateTime();

        // 计算时间差（以小时为单位）
%>
    <%
        int hid=rsheadline.getInt("hid");
        String type=rstype.getString("tname");
        String title = rsheadline.getString("title");
        int pageViews = rsheadline.getInt("page_views"); // 假设 page_views 是整数
        long hoursAgo = ChronoUnit.HOURS.between(createdLocalDateTime, now);// 计算时间差（以小时为单位）
        int publisher = rsheadline.getInt("publisher");
    %>

    newsData.push({
        "hid":"<%= hid %>",
        "title": "<%= title.replaceAll("\"", "\\\"") %>",
        "views": <%= pageViews %>,
        "hoursAgo": <%= hoursAgo %>,
        "type": "<%= type.replaceAll("\"", "\\\"") %>",
        "publisher": <%= publisher %>
    });
    <%}%>

    const itemsPerPage = 4; // 每页显示的新闻条目数
    let currentPage = 1;//初始页面
    const currentUid = <%= uid %>; // 当前用户的 uid



    function renderNewsItems(page) {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const pageData = newsData.slice(start, end);

        const newsList = document.querySelector('.news-list');
        newsList.innerHTML = '';

        pageData.forEach(item => {
            const article = document.createElement('article');
            article.className = 'news-item';

            const h2 = document.createElement('h2');
            h2.textContent = item.title;

            const p = document.createElement('p');
            p.innerHTML = `>`+item.type+ `<br>`
                +item.views+` 浏览 <br>`
                +item.hoursAgo+` 小时前`;

            const actions = document.createElement('div');
            actions.className = 'actions';

            const viewButton = document.createElement('button');
            viewButton.textContent = '查看全文';
            viewButton.addEventListener('click', function() {

                // 设置要跳转的页面 URL
                window.location.href = '/news/newShow.jsp?hid='+item.hid;
            });
            actions.appendChild(viewButton);

            if (item.publisher === currentUid) {
                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.addEventListener('click', function() {
                    // 设置要跳转的页面 URL
                    window.location.href = '/news/deleteShow.jsp?hid='+item.hid;
                });
                actions.appendChild(deleteButton);
            }


            if (item.publisher === currentUid) {
                const editButton = document.createElement('button');
                editButton.textContent = '修改';
                editButton.addEventListener('click', function() {
                    // 设置要跳转的页面 URL
                    window.location.href = '/news/updateShow.jsp?hid='+item.hid;
                });
                actions.appendChild(editButton);
            }

            article.appendChild(h2);
            article.appendChild(p);
            article.appendChild(actions);

            newsList.appendChild(article);
        });
    }

    function renderPagination(totalPages) {
        const pagination = document.querySelector('#pagination');
        pagination.innerHTML = '';

        for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = 'page-item' + (i === currentPage ? ' active' : '');
            const a = document.createElement('a');
            a.className = 'page-link';
            a.href = '#';
            a.textContent = i;
            a.addEventListener('click', () => {
                currentPage = i;
                renderNewsItems(currentPage);
                renderPagination(totalPages);
            });

            li.appendChild(a);
            pagination.appendChild(li);
        }
    }

    function init() {
        const totalPages = Math.ceil(newsData.length / itemsPerPage);
        renderNewsItems(currentPage);
        renderPagination(totalPages);
    }

    document.addEventListener('DOMContentLoaded', init);
</script>




</body>
<%}%>
</html>
